//
//  HJComposeView.swift
//  WeiBo
//
//  Created by 韩俊 on 15/12/16.
//  Copyright © 2015年 HanJun. All rights reserved.
//

import UIKit
import pop

class HJComposeView: UIView {
    
    var target: UIViewController?
    
    private lazy var buttons: [HJComposeMenuButton] = [HJComposeMenuButton]()
    
    private var composeButtonInfos:[HJComposeInfo]?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        width = SCREENW
        height = SCREENH
        
        setupUI()
        
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        //backgroundColor = UIColor(white: 0.95, alpha: 1)
        backgroundColor = randomColor()
        addSubview(bgImageView)
        addSubview(sloganImageView)
        addChildButton()
        
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
        }
        sloganImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
    }
    //监听方法
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        for (i,value) in buttons.reverse().enumerate(){
            
            anim(value, isUp: false, index: i)
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
            self.removeFromSuperview()
        })
    }
    
    @objc private func composeButtonClick(button:UIButton){
        
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            for value in self.buttons {
                value.alpha = 0.2
                if value == button {
                    //是当前button 执行放大透明
                    value.transform = CGAffineTransformMakeScale(2, 2)
                    
                }else{
                    value.transform = CGAffineTransformMakeScale(0.3, 0.3)
                }
                
            }
            
            }) { (_) -> Void in
                
                let info = self.composeButtonInfos![button.tag]
                
                if let name = info.className {
                    let cls = NSClassFromString(name) as? UIViewController.Type
                    let result = cls?.init()
                    self.target?.presentViewController(HJNavigationController(rootViewController: result!), animated: true, completion: { () -> Void in
                        self.removeFromSuperview()
                    })
                }
                
        }
    }
    
    //添加6个按钮
    private func addChildButton(){
        //定义按钮的宽高
        let childW: CGFloat = 80
        let childH: CGFloat = 110
        //计算每个按钮之间的距离
        let childMargin = (SCREENW - 3 * childW) / 4
        
        composeButtonInfos = getComposeButtonInfos()
        
        for (i,value) in composeButtonInfos!.enumerate(){
            
            let button = HJComposeMenuButton()
            
            button.addTarget(self, action: "composeButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            let icon = value.icon!
            let title = value.title!
            
            //指示显示内容
            button.setImage(UIImage(named: icon), forState: UIControlState.Normal)
            button.setTitle(title, forState: UIControlState.Normal)
            button.tag = i
            //指示大小
            button.size = CGSize(width: childW, height: childH)
            //求出当前遍历添加的按钮在第几行 第几列
            let col = i % 3
            let row = i / 3
            
            button.x = CGFloat(col+1)*childMargin + CGFloat(col)*childW
            button.y = CGFloat(row)*(childMargin+childW) + SCREENH
            
            addSubview(button)
            buttons.append(button)
        }
    }
    
    //获取按钮的信息
    private func getComposeButtonInfos() -> [HJComposeInfo]{
        //读取文件路径
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        //转成数组
        let composeButtonInfos = NSArray(contentsOfFile: path)!
        
        var result = [HJComposeInfo]()
        
        for value in composeButtonInfos {
            
            result.append(HJComposeInfo(dic: value as! [String:AnyObject]))
        }
        
        return result
        
    }
    
    func show(target:UIViewController?){
        
        self.target = target
        //let window = UIApplication.sharedApplication().windows.last
        target?.view?.addSubview(self)
        
        for (i,value) in buttons.enumerate() {
            anim(value, index: i)
        }
    }
    
    private func anim(button:UIButton,isUp: Bool = true,index:Int){
        
        let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        //终点位置
        
        let y: CGFloat = isUp ? button.center.y - 350 : button.center.y + 350
        anim.toValue = NSValue(CGPoint: CGPoint(x: button.center.x, y: y))
        //弹性度  越大  抖动幅度越大
        anim.springBounciness = 8
        //弹性速度
        anim.springSpeed = 10
        anim.beginTime = CACurrentMediaTime() + Double(index)*0.025
        button.pop_addAnimation(anim, forKey: nil)
    }
    
    // MARK: - 懒加载
    
    private lazy var bgImageView: UIImageView = UIImageView(image: UIImage.getScreentShot().applyLightEffect())
    
    // 宣传语的图片
    private lazy var sloganImageView: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    
    
}
